from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
from bs4 import BeautifulSoup
import csv
import os
import cv2
from PIL import Image
import pytesseract
import numpy as np
import sys
import PIL.Image
from pathlib import Path
import ddddocr
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import base64
from selenium.common.exceptions import TimeoutException

# ===== 添加向后兼容性代码 =====
if not hasattr(PIL.Image, 'ANTIALIAS'):
    PIL.Image.ANTIALIAS = PIL.Image.LANCZOS



def open_browser(chromedriver_path, user_data_dir):
    """打开浏览器并登录"""
    options = webdriver.ChromeOptions()
    options.add_argument(f'user-data-dir={user_data_dir}')
    service = Service(chromedriver_path)
    driver = webdriver.Chrome(service=service, options=options)
    driver.get("https://www.i-elitech.net/user/login")
    time.sleep(2)
    return driver

def extract_and_save_temperature_data(driver, CSV_FILE, MD_FILE):
    from bs4 import BeautifulSoup
    import csv
    import os

    # 提取HTML
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')

    # 提取 data-row-key 的记录（最多前 10 条）
    records = []
    rows = soup.find_all("tr", class_="ant-table-row")
    for row in rows:
        row_key = row.get("data-row-key")
        if row_key and row_key.isdigit() and int(row_key) < 10:
            cells = row.find_all("td")
            if len(cells) >= 2:
                time_str = cells[0].get_text(strip=True)
                temp_str = cells[1].get_text(strip=True)
                if '℃' in temp_str:
                    records.append((time_str, temp_str))

    # 创建 CSV 文件（如果不存在），写入表头
    if not os.path.exists(CSV_FILE):
        with open(CSV_FILE, "w", newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["时间", "温度"])

    # 读取已有数据
    existing_records = set()
    with open(CSV_FILE, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        next(reader, None)  # 跳过表头
        for row in reader:
            if len(row) >= 2:
                existing_records.add((row[0], row[1]))

    # 写入新数据（只追加新的）
    new_records = [r for r in records if r not in existing_records]
    if new_records:
        with open(CSV_FILE, "a", newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerows(new_records)

    # 读取所有记录，按时间倒序生成 Markdown 表格
    all_records = []
    with open(CSV_FILE, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        next(reader, None)  # 跳过表头
        for row in reader:
            if len(row) >= 2:
                all_records.append((row[0], row[1]))

    all_records = sorted(all_records, key=lambda x: x[0], reverse=True)

    # 写入 Markdown 表格
    markdown_lines = ["| 时间 | 温度 |", "| ---- | ---- |"]
    for time_str, temp_str in all_records:
        markdown_lines.append(f"| {time_str} | {temp_str} |")

    with open(MD_FILE, "w", encoding="utf-8") as f:
        f.write("\n".join(markdown_lines))

    print(f"✅ 写入成功，共 {len(all_records)} 条记录，新增 {len(new_records)} 条")


def login_with_captcha():
    """
    自动登录函数，处理空白页面并直接导航到主页
    """
    # 直接使用本地已安装的ChromeDriver
    options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(options=options)
    driver.maximize_window()

    # 导航到登录页面
    login_url = "https://www.i-elitech.net/user/login"
    driver.get(login_url)

    try:
        # 等待登录元素可见
        WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "userName"))
        )

        # 用户凭据
        username = "temp_d121"
        password = "D121d121d121@"

        # 填写用户名
        username_input = driver.find_element(By.ID, "userName")
        username_input.clear()
        username_input.send_keys(username)

        # 填写密码
        password_input = driver.find_element(By.ID, "accountPassword")
        password_input.clear()
        password_input.send_keys(password)

        # 获取验证码图片
        captcha_img = driver.find_element(By.CSS_SELECTOR, "img.verify-code")

        # 对于blob URL，使用JS获取图像数据
        captcha_base64 = driver.execute_script("""
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            var img = arguments[0];
            canvas.height = img.naturalHeight;
            canvas.width = img.naturalWidth;
            ctx.drawImage(img, 0, 0);
            return canvas.toDataURL('image/png').substring(22);
        """, captcha_img)

        # 将base64转换为图像供ddddocr使用
        captcha_bytes = base64.b64decode(captcha_base64)

        # 使用ddddocr识别验证码
        ocr = ddddocr.DdddOcr()
        captcha_text = ocr.classification(captcha_bytes)

        print(f"识别出的验证码: {captcha_text}")

        # 填写验证码
        captcha_input = driver.find_element(By.ID, "verCode")
        captcha_input.clear()
        captcha_input.send_keys(captcha_text)

        # 勾选同意服务协议复选框
        agree_checkbox = driver.find_element(By.ID, "agree")
        if not agree_checkbox.is_selected():
            # 有时候直接点击复选框可能不起作用，所以也可以尝试使用JavaScript点击
            try:
                agree_checkbox.click()
            except:
                driver.execute_script("arguments[0].click();", agree_checkbox)

            print("已勾选同意服务协议")
        else:
            print("服务协议复选框已经被勾选")

        # 寻找登录按钮 - 尝试多种可能的选择器
        try:
            # 首先尝试查找表单提交按钮
            login_button = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
        except:
            try:
                # 尝试查找带有登录相关类或文本的按钮
                login_button = driver.find_element(By.XPATH,
                                                   "//button[contains(@class, 'login') or contains(text(), '登录') or contains(text(), 'Login')]")
            except:
                # 最后尝试查找所有按钮，并使用靠近表单的那个
                buttons = driver.find_elements(By.TAG_NAME, "button")
                # 使用可见的且可能是表单一部分的按钮
                login_button = None
                for button in buttons:
                    if button.is_displayed():
                        login_button = button
                        break

                if not login_button:
                    print("无法定位登录按钮")
                    raise Exception("未找到登录按钮")

        # 点击登录按钮
        login_button.click()

        # 等待登录过程完成
        time.sleep(3)

        # 检查当前URL是否是空白页面（如果URL包含.data或者页面内容为空）
        if ".data" in driver.current_url or driver.page_source == "<html><head></head><body></body></html>":
            print("检测到空白页面，直接导航到主页...")
            # 直接导航到目标页面
            driver.get("https://www.i-elitech.net/home")

            # 等待页面加载完成
            time.sleep(3)

            # 检查是否成功导航到主页
            if "home" in driver.current_url:
                print("成功导航到主页!")
            else:
                print(f"导航似乎不成功，当前URL: {driver.current_url}")

                # 如果导航不成功，可能是登录状态已丢失，再次尝试登录
                if "login" in driver.current_url:
                    print("似乎需要重新登录，返回到登录函数...")
                    # 这里可以选择重新调用登录函数，或者给出提示
                    print("请手动刷新页面或重新运行脚本")
        else:
            print(f"登录后当前URL: {driver.current_url}")
            # 如果当前页面不是主页，但也不是空白页，可以选择是否导航到主页
            if "/home" not in driver.current_url:
                print("当前不在主页，尝试导航到主页...")
                driver.get("https://www.i-elitech.net/home")
                time.sleep(2)

        print("登录流程已完成，您现在可以继续后续操作")
        return driver

    except Exception as e:
        print(f"登录过程中出错: {e}")
        return driver


def click_data_window_buttons(driver, timeout=30):
    """
    依次点击"在线设备"->"1030"->"数据图表"按钮，使用准确的HTML元素选择器。

    :param driver: Selenium webdriver 已登录并位于目标页面
    :param timeout: 每次等待元素出现的最长秒数
    """
    wait = WebDriverWait(driver, timeout)

    # 确保页面完全加载
    print("等待页面完全加载...")
    time.sleep(8)  # 增加等待时间

    # 打印页面信息，帮助调试
    print(f"当前页面标题: {driver.title}")
    print(f"当前页面URL: {driver.current_url}")

    try:
        # 1. 点击"在线设备"，使用精确的CSS选择器
        print("尝试点击'在线设备'按钮...")

        # 使用基于您提供的HTML的精确CSS选择器
        online_device_selector = "div[data-v-6df84650].box"

        # 先尝试找到元素并显示它
        online_device_element = None
        try:
            # 检查元素是否存在
            online_device_elements = driver.find_elements(By.CSS_SELECTOR, online_device_selector)
            print(f"找到 {len(online_device_elements)} 个匹配'在线设备'的元素")

            if len(online_device_elements) > 0:
                # 查找包含"在线设备"文本的元素
                for element in online_device_elements:
                    if "在线设备" in element.text:
                        online_device_element = element
                        print(f"找到'在线设备'元素，文本内容: {element.text}")
                        break

            if not online_device_element:
                print("未找到包含'在线设备'文本的元素，尝试其他方法...")

        except Exception as e:
            print(f"查找'在线设备'元素时出错: {e}")

        # 如果未找到元素，尝试备用方法
        if not online_device_element:
            # 尝试 XPATH
            try:
                online_device_element = driver.find_element(By.XPATH,
                                                            "//div[contains(@class, 'box')][.//p[contains(@class, 'title') and text()='在线设备']]")
                print("使用XPATH找到'在线设备'元素")
            except:
                # 尝试JavaScript
                print("尝试使用JavaScript查找'在线设备'元素...")
                driver.execute_script("""
                    var elements = document.querySelectorAll('p.title');
                    for (var i = 0; i < elements.length; i++) {
                        if (elements[i].textContent.trim() === '在线设备') {
                            elements[i].closest('div.box').style.border = '3px solid red';
                            elements[i].closest('div.box').scrollIntoView({behavior: "smooth", block: "center"});
                            return elements[i].closest('div.box');
                        }
                    }
                """)
                time.sleep(2)  # 让页面滚动并高亮元素

                # 尝试使用JavaScript点击
                result = driver.execute_script("""
                    var elements = document.querySelectorAll('p.title');
                    for (var i = 0; i < elements.length; i++) {
                        if (elements[i].textContent.trim() === '在线设备') {
                            var boxElement = elements[i].closest('div.box');
                            if (boxElement) {
                                boxElement.click();
                                return true;
                            }
                        }
                    }
                    return false;
                """)

                if result:
                    print("使用JavaScript成功点击了'在线设备'元素")
                else:
                    print("JavaScript也无法点击'在线设备'元素")
                    raise Exception("无法找到'在线设备'按钮")

        # 如果找到元素但尚未点击，现在点击它
        if online_device_element:
            # 确保元素可见
            driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});",
                                  online_device_element)
            time.sleep(1)

            try:
                # 先用Selenium点击
                print("尝试用Selenium点击'在线设备'元素...")
                online_device_element.click()
            except:
                # 如果失败，使用JavaScript点击
                print("Selenium点击失败，尝试用JavaScript点击...")
                driver.execute_script("arguments[0].click();", online_device_element)

            print("已点击'在线设备'按钮")

        # 等待UI响应
        time.sleep(5)

        # 2. 点击"1030"设备按钮，使用精确的选择器
        print("尝试点击'1030'设备按钮...")

        # 使用基于您提供的HTML的精确选择器
        device_selector = "span.device-name"

        try:
            # 等待元素出现并可点击
            device_element = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, device_selector))
            )

            # 检查文本内容
            device_elements = driver.find_elements(By.CSS_SELECTOR, device_selector)
            print(f"找到 {len(device_elements)} 个设备名称元素")

            device_1030 = None
            for element in device_elements:
                if "1030" in element.text:
                    device_1030 = element
                    print(f"找到设备元素，文本内容: {element.text}")
                    break

            if device_1030:
                # 确保元素可见
                driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});",
                                      device_1030)
                time.sleep(1)

                try:
                    # 尝试点击元素
                    device_1030.click()
                except:
                    # 如果直接点击失败，尝试JavaScript点击
                    print("直接点击失败，尝试JavaScript点击...")
                    driver.execute_script("arguments[0].click();", device_1030)

                print("已点击'1030'设备按钮")
            else:
                # 如果没有找到精确匹配的元素，尝试使用JavaScript查找和点击
                print("未找到文本包含'1030'的设备元素，尝试使用JavaScript...")
                result = driver.execute_script("""
                    var elements = document.querySelectorAll('span.device-name');
                    for (var i = 0; i < elements.length; i++) {
                        if (elements[i].textContent.includes('1030')) {
                            elements[i].click();
                            return true;
                        }
                    }
                    return false;
                """)

                if result:
                    print("使用JavaScript成功点击了'1030'设备")
                else:
                    print("无法找到并点击'1030'设备")
        except Exception as e:
            print(f"查找并点击'1030'设备时出错: {e}")
            # 尝试其他方法
            try:
                # 尝试XPATH
                device_1030 = driver.find_element(By.XPATH,
                                                  "//span[contains(@class, 'device-name') and contains(text(), '1030')]")
                device_1030.click()
                print("使用XPATH成功点击了'1030'设备")
            except:
                print("XPATH方法也失败了")

        # 等待UI响应
        time.sleep(5)

        # 3. 点击"数据图表"Tab
        print("尝试点击'数据图表'标签...")

        # 使用基于您提供的HTML的精确选择器
        tab_selector = "div.ant-tabs-tab"

        try:
            # 查找所有标签
            tabs = driver.find_elements(By.CSS_SELECTOR, tab_selector)
            print(f"找到 {len(tabs)} 个标签")

            data_chart_tab = None
            for tab in tabs:
                if "数据图表" in tab.text:
                    data_chart_tab = tab
                    print(f"找到数据图表标签，文本内容: {tab.text}")
                    break

            if data_chart_tab:
                # 确保元素可见
                driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});",
                                      data_chart_tab)
                time.sleep(1)

                try:
                    # 尝试点击元素
                    data_chart_tab.click()
                except:
                    # 如果直接点击失败，尝试JavaScript点击
                    print("直接点击失败，尝试JavaScript点击...")
                    driver.execute_script("arguments[0].click();", data_chart_tab)

                print("已点击'数据图表'标签")
            else:
                # 如果没有找到精确匹配的元素，尝试使用JavaScript查找和点击
                print("未找到文本为'数据图表'的标签，尝试使用JavaScript...")
                result = driver.execute_script("""
                    var tabs = document.querySelectorAll('div[role="tab"]');
                    for (var i = 0; i < tabs.length; i++) {
                        if (tabs[i].textContent.trim() === '数据图表') {
                            tabs[i].click();
                            return true;
                        }
                    }
                    return false;
                """)

                if result:
                    print("使用JavaScript成功点击了'数据图表'标签")
                else:
                    print("无法找到并点击'数据图表'标签")
        except Exception as e:
            print(f"查找并点击'数据图表'标签时出错: {e}")
            # 尝试XPATH
            try:
                tab = driver.find_element(By.XPATH, "//div[@role='tab' and contains(text(), '数据图表')]")
                tab.click()
                print("使用XPATH成功点击了'数据图表'标签")
            except:
                print("XPATH方法也失败了")

        print("点击操作序列完成")
        return True

    except Exception as e:
        print(f"在点击操作过程中遇到错误: {e}")
        return False
# 配置参数
CHROMEDRIVER_PATH = r'D:\chromedriver-win64\chromedriver-win64\chromedriver.exe'    # ChromeDriver 路径
USER_DATA_DIR = r'D:\User Data'                                                     # Chrome 用户数据目录,默认是 C:\用户\用户名\AppData\Local\Google\Chrome\User Data，需要复制出来一份，否则不能跳转网页
CSV_FILE = r"C:\Users\guozt\Desktop\temperature\temperature_data.csv"               #保存的 CSV 文件路径
MD_FILE = r"C:\Users\guozt\Desktop\temperature\temperature_data.md"

login_with_captcha()
driver = webdriver.Chrome()
click_data_window_buttons(driver)